*!Version 1.0.0 2Aug05

*this program is similar to stata's cumul

program define jcumul, sortpreserve
	version 9.0

	syntax varname [if] [in] [aweight fweight /],  [by(str)] Generate(str) 
	confirm new var `generate'

	local varname `varlist'

	/* mark sample */
	marksample touse 
	qui count if `touse'
	local Nboth = _result(1)

	local treat
	local cats 1
	if "`by'"~="" {
		qui tab `by'
		local cats = _result(2)
		local treat "`by'"
	}
	else {
		local treat "1"
	}

	if `cats'>2 {
		di in red "Your by variable `by' has more than 2 categories."
		error
	}

	*create `weight' = 2 if no weights specified
	tempname weightexp
	if "`weight'"=="" {
 		qui gen `weightexp' = 1 if `touse' & `cats'==1 	/* not using by */ 
 		qui gen `weightexp' = 2 if `touse' & `cats'==2	/* using by */
	}
	else { /* user supplied weights. we check to see if they vary at all */ 
		qui gen double `weightexp'=`exp'
		qui sum `weightexp' if `touse'
		if _result(4)==0 { /* need to reset weights to 1 or 2 in this case */
	di " -> -jcumul-: constant weights, so using correctly scaled weight  "
	 		qui replace `weightexp' = 1 if `touse' & `cats'==1 	/* not using by */ 
 			qui replace `weightexp' = 2 if `touse' & `cats'==2	/* using by */
		} /* done resetting weights */
	} /* done dealing with weights */

	*first we sort the data by `varname' and treatment var
	qui sort `varname'
	
	*now we sum weight up to this value
	tempname cdf
	qui generate double `cdf' = sum(`weightexp'*(`treat'==1)) if `touse' & `treat'==1
	qui replace  	`cdf' = sum(`weightexp'*(`treat'==0)) if `touse' & `treat'==0
	
	qui replace `cdf' = `cdf'/`Nboth'

	qui gen double `generate' = `cdf'

end

